<template>
  <el-input
    ref="dosageInputRef"
    class="c-dosage-and-unit"
    :class="{ 'hidden-input': disableDosage }"
    v-model="localDosage"
    type="number"
    :placeholder="placeholder"
    :clearable="clearable"
    @wheel.stop.prevent
    v-number-valid="{
      digit: props.digit,
      canNegative: props.canNegative
    }"
    :disabled="props.disabled || disableDosage"
    @change="handleChangeDosage"
    @keypress.enter="handleKeypressEnter"
  >
    <template #append>
      <CSelect
        class="c-dosage-and-unit-select"
        v-model="localUnit"
        :disabled="props.disabled || props.unitDisabled"
        filterable
        @change="handleChangeUnit"
      >
        <template v-if="props.isGroup">
          <el-option-group
            v-for="unitGroup in unitGroupOptions"
            :key="unitGroup.name"
            :label="unitGroup.name"
          >
            <el-option
              v-for="unit in unitGroup.options"
              :key="unit.value"
              :label="unit.label"
              :value="unit.value"
            />
          </el-option-group>
        </template>
        <template v-else>
          <el-option
            v-for="unit in unitOptions"
            :key="unit.value"
            :label="unit.label"
            :value="unit.value"
          />
        </template>
      </CSelect>
    </template>
  </el-input>
</template>

<script lang="ts" setup name="CDosageAndUnit">
import { withDefaults, defineProps, defineEmits, computed, ref, watch } from 'vue';
import {
  modelUnitAllByGroupOption,
  modelUnitAllNoPcsByGroupOption,
  TransportUnitOption,
  DistanceUnitOption,
  WeightUnitOption
} from '@/constants/enum';
import { CSelect } from '@/components/CSelect';

/**
 * 单位类型
 * 所有｜所有除了pcs｜重量｜运输｜距离
 */
type UnitType = 'ALL' | 'ALL_WITHOUT_PCS' | 'WEIGHT' | 'TRANSPORT' | 'DISTANCE';

interface FlowDialogProps {
  /**
   * 用量
   */
  dosage: any;
  /**
   * 单位
   */
  unit: string;
  /**
   * 占位文字
   */
  placeholder?: string;
  /**
   * 单位类型
   */
  unitType?: UnitType;
  /**
   * 单位列表
   */
  // eslint-disable-next-line no-undef
  unitOption?: any[];
  /**
   * 禁用
   */
  disabled?: boolean;
  unitDisabled?: boolean;
  /**
   * 保留位数
   */
  digit?: number;
  /**
   * 能否为负数
   */
  canNegative?: boolean;
  /**
   * 是否是组
   */
  isGroup?: boolean;
  /**
   * 是否处理pcs特殊情况，当选择pcs,dosage返回null,并且不可输入
   */
  dealPcs?: boolean;
  /**
   * 是否可以清空
   */
  clearable?: boolean;
}
const props = withDefaults(defineProps<FlowDialogProps>(), {
  placeholder: '请输入',
  unitType: 'ALL',
  disabled: false,
  digit: 6,
  canNegative: true,
  isGroup: false,
  dealPcs: false,
  clearable: true
});
const emits = defineEmits(['update:dosage', 'update:unit', 'changeDosage', 'changeUnit']);

const dosageInputRef = ref();
/**
 * 用量
 */
const localDosage = computed({
  get() {
    return props.dosage;
  },
  set(val) {
    emits('update:dosage', val);
  }
});

/**
 * 单位
 */
const localUnit = computed({
  get() {
    return props.unit;
  },
  set(val) {
    emits('update:unit', val);
  }
});

/**
 * 用量
 */
const disableDosage = computed(() => {
  return !!props.dealPcs && localUnit.value == 'pcs';
});
// eslint-disable-next-line no-undef
const unitOptions = computed<LabelValueOptions>(() => {
  if (props.unitOption?.length) {
    return props.unitOption;
  }
  switch (props.unitType) {
    case 'TRANSPORT':
      return TransportUnitOption;
    case 'DISTANCE':
      return DistanceUnitOption;
    case 'WEIGHT':
      return WeightUnitOption;
    default:
      return [];
  }
});

/**
 * 单位分组
 */
const unitGroupOptions = computed(() => {
  if (props.isGroup) {
    if (props.unitOption?.length) {
      return props.unitOption;
    }
    switch (props.unitType) {
      case 'ALL':
        return modelUnitAllByGroupOption;
      case 'ALL_WITHOUT_PCS':
        return modelUnitAllNoPcsByGroupOption;
      default:
        return [];
    }
  } else {
    return [];
  }
});
const originalVal = ref('');

watch(
  () => props.dosage,
  val => {
    if (props.dealPcs && localUnit.value !== 'pcs') {
      originalVal.value = val;
    }
  }
);
function handleChangeDosage(val: string) {
  originalVal.value = val;
  emits('changeDosage', localDosage.value);
}

function handleKeypressEnter() {
  dosageInputRef.value?.blur();
}

function handleChangeUnit(val: string) {
  if (props.dealPcs) {
    if (val == 'pcs') {
      localDosage.value = '-';
    } else {
      localDosage.value = JSON.parse(JSON.stringify(originalVal.value));
    }
  }
  emits('changeUnit', localUnit.value);
}
</script>

<style lang="scss" scoped>
.c-dosage-and-unit {
  width: 100%;
  .c-dosage-and-unit-select {
    width: 120px;
  }
  :deep(.el-input-group__append, .el-input-group__prepend) {
    background: transparent;
  }
  :deep(.el-select .el-input .el-input__wrapper) {
    border-left: 1px solid var(--el-input-border-color);
  }
}
// :deep(.hidden-input:first-child) {
//   background: red;
// }
.hidden-input > :first-child {
  // :deep(.el-input__wrapper) {
  display: none;
  // }
}
</style>
